<template>
  <div class="w100%">
    <div class="wang-editor-container h400px b b-1px b-solid b-#ccc">
      <toolbar :editor="editorRef" style="border-bottom: 1px solid var(--el-border-color)" />
      <editor v-model="html" class="wang-editor-content w100%!" :default-config="editorConfig" @on-created="handleCreated" />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { IDomEditor } from '@wangeditor/editor'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'

defineOptions({
  name: 'WangEditor',
})

const emit = defineEmits(['update:modelValue'])

const props = withDefaults(
  defineProps<{
    modelValue: string
  }>(),
  {}
)
const html = computed({
  get: () => props.modelValue,
  set: (val) => {
    emit('update:modelValue', val)
  },
})

const baseUrl = `${import.meta.env.VITE_APP_BASE_URL}`
const $baseMessage = inject<any>('$baseMessage')
const $baseAlert = inject<any>('$baseAlert')
const editorRef = shallowRef<IDomEditor | undefined>(undefined)
const editorConfig = reactive<any>({
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      server: `${baseUrl}/api/ossPut`, // 您的服务器地址，注意：当前接口格式特殊与其他vab接口不同，请查看vip文档
      fieldName: 'file',
      allowedFileTypes: ['image/*'],
      headers: {}, // 如需传递token请写到在这里
      customInsert(res: any, insertFn: any) {
        if (res.status == 200) {
          insertFn(res.url)
        } else {
          $baseMessage(res.message, 'error')
        }
      },
    },
    uploadVideo: {
      server: `${baseUrl}/api/ossPut`, // 您的服务器地址，注意：当前接口格式特殊与其他vab接口不同，请查看vip文档
      fieldName: 'file',
      allowedFileTypes: ['video/*'],
      maxFileSize: 15 * 1024 * 1024, //15m
      headers: {}, // 如需传递token请写到在这里
      customInsert(res: any, insertFn: any) {
        if (res.status == 200) {
          insertFn(res.url)
        } else {
          $baseMessage(res.message, 'error')
        }
      },
    },
  },
})

const handleCreated = (editor: IDomEditor) => {
  editorRef.value = editor
}

const onSubmit = () => {
  $baseAlert(html.value)
  $baseMessage('模拟保存成功', 'success', 'hey')
}

onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
</script>

<style lang="scss">
.wang-editor-container {
  padding: 0 !important;
  overflow: hidden !important;
  [classname='w-e-toolbar-init'] {
    border-bottom: 1px solid var(--el-border-color) !important;
  }
  .w-e-text-container {
    margin: 0 !important;
    min-height: calc(100% - 81px) !important;
  }
  .wang-editor-content {
    width: 70%;
    height: calc(100% - 81px) !important;
    border: 0;
  }
  .w-e-textarea-1 {
  }
  .wang-editor-footer {
    width: 70%;
    margin: auto;
  }

  @media (max-width: 576px) {
    .wang-editor-title,
    .wang-editor-content,
    .wang-editor-footer {
      width: 90%;
    }
  }
}
</style>
